const { TypeGuards, evalQuotedToken, evalToken } = require('liquidjs');
const { theme } = require('../config');
const fs = require('fs');
const path = require('path');


const { env } = require('process');


function optimize(templates) {
  // for filenames like "files/file.liquid", extract the string directly
  if (templates.length === 1 && TypeGuards.isHTMLToken(templates[0].token)) return templates[0].token.getContent();
  return templates;
}

function renderFilePath(file, ctx, liquid) {
  if (typeof file === 'string') return file;
  if (Array.isArray(file)) return liquid.renderer.renderTemplates(file, ctx);
  return evalToken(file, ctx);
}
function parseFilePath(tokenizer, liquid) {
  if (liquid.options.dynamicPartials) {
    const file = tokenizer.readValue();
    if (file === undefined) throw new TypeError(`illegal argument "${tokenizer.input}"`);
    if (file.getText() === 'none') return null;
    if (TypeGuards.isQuotedToken(file)) {
      // for filenames like "files/{{file}}", eval as liquid template
      const templates = liquid.parse(evalQuotedToken(file));
      return optimize(templates);
    }
    return file;
  }
  const tokens = [...tokenizer.readFileNameTemplate(liquid.options)];
  const templates = optimize(liquid.parser.parseTokens(tokens));
  return templates === 'none' ? null : templates;
}

function assert(predicate, message) {
  if (!predicate) {
    const msg = typeof message === 'function' ? message() : message || `expect ${predicate} to be true`;
    throw new AssertionError(msg);
  }
}

const devPath = function (path) {
  if (!fsExistsSync(`./src/theme/${theme.getTheme() }${path}`)) {
    return defaultPath(path);
  }
  return `./src/theme/${theme.getTheme() }${path}`;
};

const defaultPath = function (path) {
  return `./src/theme/default${path}`;
};

// const buildPath = function (path) {
//     return `${buildRoot}/${root}${path}`;
// };


function readFile(targetFile) {
  if (!fsExistsSync(targetFile)) {
    return '';
  }
  return fs.readFileSync(targetFile, 'utf-8');
}

function writeFile(targetFile, content) {
  const dir = path.dirname(targetFile);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
  fs.writeFileSync(targetFile, content);
}

function fsExistsSync(dir) {
  if (!fs.existsSync(dir)) {
    // console.log("文件查找失败：" + dir);
    return false;
  }
  return true;
}

function getBlockSchema(name) {
  let dir = devPath(`/sections/${name}.liquid`);
  if (!fs.existsSync(dir)) {
    console.log('积木块路由不存在', dir);
    return '';
  }
  var content = fs.readFileSync(dir, 'utf-8');
  const schemaRegExpStr = /{% schema %}([\s\S]*?){% endschema %}/g;
  const schemBody = content.match(schemaRegExpStr);
  if (schemBody) {
    content = JSON.parse(schemBody[0].replace(/({% schema %})|({% endschema %})/g, ''));
  }
  return content;
}

function getPathBlockSchema(path) {
  if (!fs.existsSync(path)) {
    console.log('积木块路由不存在', path);
    return '';
  }
  var content = fs.readFileSync(path, 'utf-8');
  const schemaRegExpStr = /{% schema %}([\s\S]*?){% endschema %}/g;
  const schemBody = content.match(schemaRegExpStr);
  if (schemBody) {
    content = JSON.parse(schemBody[0].replace(/({% schema %})|({% endschema %})/g, ''));
  }
  return content;
}



function getBlockSections(route) {

  let block_sections = [];

  // 积木块开发模式
  if (env.NODE_ENV_BLOCK === 'dev') {
    const testConfig = JSON.parse(fs.readFileSync(devPath('/lib/config/test.json'), 'utf-8'));
    return testConfig.block;
  }

  let roterSections = [];

  const routeFileName = route.replace('/','_');
  if (fs.existsSync(devPath(`/lib/config/${routeFileName}.json`))) {
    roterSections = JSON.parse(fs.readFileSync(devPath(`/lib/config/${routeFileName}.json`), 'utf-8'));
  } else {
    const settingsData = JSON.parse(fs.readFileSync(devPath('/config/settings_data.json'), 'utf-8'));
    roterSections = settingsData.pages_settings.filter((el) => el.route === route && !['header', 'footer'].includes(el.type))[0].sections;
  }
  // const settingsSchema = JSON.parse(fs.readFileSync(devPath("/config/settings_schema.json"), "utf-8"));


  // const settingsSchema = JSON.parse(fs.readFileSync(devPath("/config/settings_schema.json"), "utf-8"));
  // let roterSections = [];
  // if (fs.existsSync(devPath("/lib/config/page.json"))) {
  //     const settingsData = JSON.parse(fs.readFileSync(devPath("/lib/config/page.json"), "utf-8"));
  //     roterSections = settingsData.filter((el) => el.route === route && !["header", "footer"].includes(el.type));
  // } else {
  //     const settingsData = JSON.parse(fs.readFileSync(devPath("/config/settings_data.json"), "utf-8"));
  //     roterSections = settingsData.pages_settings.filter((el) => el.route === route && !["header", "footer"].includes(el.type));
  // }

  // const roterSections = settingsData.filter((el) => el.route === route && !['header','footer'].includes(el.type));

  // const currentSettingsData = settingsData.pages_settings.filter((el) => el.route === route && !['header','footer'].includes(el.type));
  if (roterSections.length) {
    block_sections = roterSections.map((item, index) => {
      var content = getBlockSchema(item.type);
      // if(currentSettingsData.length){
      //     const data = currentSettingsData[0].sections.find(item=>item.type === item.type);
      //     if(data && data.params){

      //         // content.default = data.params
      //     }
      // }
      item['id'] = index * 1000 + Math.floor(Math.random() * 1000);
      item['settings'] = content;

      if (!item.params) {
        item.params = content.default;
      }
      return item;
    });
  }
  return block_sections;
}

module.exports = { assert, fsExistsSync,readFile, defaultPath, parseFilePath, getBlockSchema,getPathBlockSchema, optimize, renderFilePath, getBlockSections, devPath, writeFile };
